package datasource

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"imooc.com/demo-lottery/conf"
	"log"
	"sync"
)

/*
 * 数据库这一块记得的把 _ "github.com/go-sql-driver/mysql" 驱动文件导入
 */

var masterInstance *xorm.Engine
var dbLock sync.Mutex

func InstanceDbMaster() *xorm.Engine {
	if masterInstance != nil {
		return masterInstance
	}

	dbLock.Lock()
	defer dbLock.Unlock()
	// 锁定之后再加一步判断，因为加锁要花时间，
	// 这期间masterInstance可能被其他goroutine初始化
	if masterInstance != nil {
		return masterInstance
	}
	return NewDbMaster()
}

func NewDbMaster() *xorm.Engine {
	sourceName := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8",
		conf.DbMaster.User,
		conf.DbMaster.Pwd,
		conf.DbMaster.Host,
		conf.DbMaster.Port,
		conf.DbMaster.Database)
	instance, err := xorm.NewEngine(conf.DriverName, sourceName)
	if err != nil {
		log.Fatal("dbhelper.NewDbMaster error=", err)
		return nil
	}

	if err = instance.Ping(); err != nil {
		log.Fatal("dbhelper.NewDbMaster.Ping error=", err)
		return nil
	}

	// 展示 sql 语句，调试时候用，上线就不展示了
	instance.ShowSQL(true)

	masterInstance = instance
	return masterInstance
}
